﻿#define DEBUG_AGENT

using System.Windows;
using Microsoft.Phone.Scheduler;
using System.Device.Location;
using System;
using Microsoft.Phone.Shell;

namespace Hangout.Client.BackgroundAgent
{
    public class ScheduledAgent : ScheduledTaskAgent
    {

        GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);


        private static volatile bool _classInitialized;

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            
            
               //Add code to perform your task in background
                watcher.PositionChanged += new System.EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
                watcher.Start();
                #if DEBUG_AGENT
                ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(5));
                #endif
               
        }

        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            
           if (watcher.Status == GeoPositionStatus.Ready)
           {
               watcher.PositionChanged -= new System.EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
               //connect to the server here and update the position :)
               UserLocationService.UserLocationServiceClient client = new UserLocationService.UserLocationServiceClient();
               UserLocationService.Location location = new UserLocationService.Location();
               if (double.IsNaN(e.Position.Location.Latitude))
               {
                   return;
               }
               location.Latitude = e.Position.Location.Latitude;

               if (double.IsNaN(e.Position.Location.Longitude))
               {
                   return;
               }


               location.Longitude = e.Position.Location.Longitude;
               
               location.UserID = Settings.UserID;
               client.UpdateUserLocationAsync(location,Settings.FacebookAccessToken);

               watcher.Stop();

              
               NotifyComplete();
           }

        }

        
    }
}